package com.shanghaionstar.nav.presenter;

import android.content.res.Resources;
import android.text.TextUtils;

import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.map.common.PoiItemInfo;
import com.shanghaionstar.R;
import com.shanghaionstar.nav.iview.INavMyFootPrintView;
import com.shanghaionstar.nav.model.FootPrintMapOperation;
import com.shanghaionstar.nav.model.FootPrintModel;
import com.shanghaionstar.nav.model.MyFootprintDTO;
import com.shanghaionstar.nav.model.MyFootprintStatisticDTO;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.utils.MapHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscription;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by 6335yz on 2016/7/25.
 */
public class NavFootPrintPresenter extends BasePresenter implements MapHandler.OnMapFootPrintCallBack {

    private AbstractMapActivity mapActivity;
    private Resources res;
    private INavMyFootPrintView navMyFootPrintView;
    private MapHandler mapHandler;
    private NavService navService;
    private LogManager log = LogManager.getInstance();

    private List<FootPrintModel> summaryPois = new ArrayList<FootPrintModel>();
    private List<FootPrintModel> showCityPois = new ArrayList<FootPrintModel>();

    private Marker currentMarker;
    private Map<String, List<FootPrintModel>> latLngListMap = new HashMap<>();
    private Map<String, FootPrintModel> cityLatLng = new HashMap<>();

    private String currentSeqId;//当前概略城市足迹坐标

    private Subscription detailShareSubscription, overViewShareSubscription;

    @Override
    public void setView(IMVPView view) {
        navMyFootPrintView = (INavMyFootPrintView) view;
        super.setView(navMyFootPrintView);
    }

    public NavFootPrintPresenter(IMVPScheduler mvpScheduler, AbstractMapActivity mapActivity, MapHandler mapHandler) {
        super(mvpScheduler);
        this.mapActivity = mapActivity;
        this.mapHandler = mapHandler;
        res = mapActivity.getResources();
        navService = new NavService(mapActivity);
        mapHandler.registOnMapFootPrintCallBack(this);
    }

    private List<MyFootprintStatisticDTO> test() {
        List<MyFootprintStatisticDTO> s = new ArrayList<>();
        MyFootprintStatisticDTO dto = new MyFootprintStatisticDTO();
        dto.setCityCount("12345");
        dto.setDestCity("上海");
        dto.setDestStreetName("12345街");
        dto.setDestStreetNum("12345号");
        dto.setLastDestLatitude("31.168149");
        dto.setLastDestLongitude("121.397208");
        dto.setStateCount("111");
        dto.setTotalCount("2");
        dto.setTotalRank("3");
        dto.setVin("123456789");
        s.add(dto);
        return s;
    }


    public void doGetPoiSummary() {
        Subscription subscription = navService.doGetFootPrintSummary()
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<List<MyFootprintStatisticDTO>>() {
                    @Override
                    public void call(List<MyFootprintStatisticDTO> s) {
//                        s = produceSummaryTestData();
                        if (s == null || s.isEmpty())
                            navMyFootPrintView.showNoPoi();
                        else {
                            getAllCityPois(s);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        navMyFootPrintView.showErr(throwable);
                    }
                });
        compositeSubscription.add(subscription);
    }

    /**
     * 测试数据
     *
     * @return
     */
    private List<MyFootprintStatisticDTO> produceSummaryTestData() {
        List<MyFootprintStatisticDTO> list = new ArrayList<>();
        MyFootprintStatisticDTO dto;
        String[] lats = {"31.2208248236", "39.8835369769"};
        String[] lngs = {"121.4679501728", "116.4082967289"};
//        for (int i = 0; i < 1; i++) {
        int i = 5;
        dto = new MyFootprintStatisticDTO();
        dto.setTotalRank(i + "");
        dto.setCityRank(i * 2 + "");
        dto.setTotalCount(i + "");
        dto.setCityCount(i + "");
        dto.setDestCity("上海");
        dto.setLastDestLatitude(lats[0]);
        dto.setLastDestLongitude(lngs[0]);
        list.add(dto);

        i = 3;
        dto = new MyFootprintStatisticDTO();
        dto.setTotalRank(i + "");
        dto.setCityRank(i * 2 + "");
        dto.setTotalCount(i + "");
        dto.setCityCount(i + "");
        dto.setDestCity("北京");
        dto.setLastDestLatitude(lats[1]);
        dto.setLastDestLongitude(lngs[1]);
        list.add(dto);
//        }
        return list;
    }

    int count[];
    private void getAllCityPois(List<MyFootprintStatisticDTO> list) {
        String totalRank = "";
        String totalCount = "";
        int cityCount = 0;
        count=new int[list.size()];
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                count[i]=Integer.valueOf(list.get(i).getCityCount());

                MyFootprintStatisticDTO myFootprintStatisticDTO = list.get(i);
                LatLng latLng = new LatLng(Double.valueOf(myFootprintStatisticDTO.getLastDestLatitude()), Double.valueOf(myFootprintStatisticDTO.getLastDestLongitude()));
                totalRank = myFootprintStatisticDTO.getTotalRank();
                totalCount = myFootprintStatisticDTO.getTotalCount();

                FootPrintModel footPrintModel = new FootPrintModel();
                footPrintModel.latLng = latLng;
                footPrintModel.cityName = myFootprintStatisticDTO.getDestCity();
                footPrintModel.isLastPoint = true;
//                footPrintModel.poiCount = totalCount + mapActivity.getString(R.string.nav_foot_print_pois);
                footPrintModel.seqId = Constants.FAKE_SEQ_ID_PREFIX + i;
                footPrintModel.cityCount = list.size();
                footPrintModel.poiCountInCity = myFootprintStatisticDTO.getCityCount();
//                footPrintModel.cityCount = Integer.valueOf(myFootprintStatisticDTO.getTotalCount());
                footPrintModel.poiCount = totalCount;
                footPrintModel.rank = totalRank;
                footPrintModel.cityRank = myFootprintStatisticDTO.getCityRank();
                /**
                 * 概略点对于的seqid，因为后台没有传相关seqid，所以自定义一个，用于表示对应得概略足迹点。
                 */
                cityLatLng.put(footPrintModel.seqId, footPrintModel);
                log.i("概略点seqid->footprintmodel map" + cityLatLng);
                /**
                 * 概略点列表
                 */
                summaryPois.add(footPrintModel);
                log.i("概略点列表" + cityLatLng);
            }
        }
        if (navMyFootPrintView != null && summaryPois.size() > 0) {
            navMyFootPrintView.showAllCityPoi(summaryPois, true);
            /**
             * 用于展示底部bottom的字段们
             */
//            FootPrintModel footPrintModel = new FootPrintModel();
//            footPrintModel.rank = totalRank + "%";
//            footPrintModel.poiCount = totalCount + mapActivity.getString(R.string.nav_foot_print_pois);
//            footPrintModel.title = cityCount + mapActivity.getString(R.string.nav_foot_print_citys);
//            navMyFootPrintView.showBottomMsg(footPrintModel);
            showSummaryBottom();
        }
    }

    public void showSummaryBottom() {
        if (navMyFootPrintView != null && summaryPois.size() > 0) {
            /**
             * 用于展示底部bottom的字段们
             */
            FootPrintModel footPrintModel = summaryPois.get(0);
            FootPrintModel showFootPrintModel = new FootPrintModel();
            showFootPrintModel.rank = footPrintModel.rank + "%";

            int myCout = 0;
            for (int i = 0; i < count.length; i++) {
                myCout+=count[i];
            }
            showFootPrintModel.poiCount = myCout + mapActivity.getString(R.string.nav_foot_print_pois);
            showFootPrintModel.title = footPrintModel.cityCount + mapActivity.getString(R.string.nav_foot_print_citys);
            navMyFootPrintView.showBottomMsg(showFootPrintModel);
        }
    }

    /**
     * @param seqId 概略点的seqid，
     * @return 查找对于的概略点的城市所有内的足迹
     */
    public int getCurrentShowCityPois(final String seqId, FootPrintMapOperation operation) {
        if (seqId == null) return 0;
        showCityPois = latLngListMap.get(seqId);
        currentSeqId = seqId;
        if (showCityPois == null || showCityPois.size() == 0) {
            doGetCityFootPrints(getCityNameBySeqId(seqId), seqId, operation);
        } else {
            if (navMyFootPrintView != null) {
                navMyFootPrintView.showCityPoi(showCityPois, operation);
                if (showCityPois != null && showCityPois.size() > 0) {
                    log.i("curent city's pois in detail" + showCityPois + ",seqId=" + seqId + ",operation=" + operation.name());
                    FootPrintModel footPrintModel = new FootPrintModel();
                    footPrintModel.title = showCityPois.get(0).cityName;
                    setCityRank(footPrintModel);
                    footPrintModel.poiCount = getPoiCountBySeqId(seqId) + mapActivity.getString(R.string.nav_foot_print_pois);
//                    footPrintModel.poiCount = String.valueOf(showCityPois.size()) + mapActivity.getString(R.string.nav_foot_print_pois);
                    navMyFootPrintView.showBottomMsg(footPrintModel);
                    return showCityPois.size();
                }
            }
        }
        return 0;
    }

    public void getSummaryCityPois(Marker marker, final String seqId) {
        if (seqId == null) return;
        showCityPois = latLngListMap.get(seqId);
        currentSeqId = seqId;
        marker.setObject(null);
        if (showCityPois == null || showCityPois.size() == 0) {
            doGetCityFootPrints(getCityNameBySeqId(seqId), seqId, FootPrintMapOperation.SHOW_SUMMARY_WINDOW_INFO, marker);
        } else {
            if (navMyFootPrintView != null) {
                navMyFootPrintView.showSummaryWindowInfo(marker, getSummaryFootPrintModel(seqId));
                if (showCityPois != null && showCityPois.size() > 0) {
                    log.i("curent city's pois in summary" + showCityPois + ",seqId=" + seqId);
                    FootPrintModel footPrintModel = new FootPrintModel();
                    footPrintModel.title = showCityPois.get(0).cityName;
                    setCityRank(footPrintModel);
//                    footPrintModel.poiCount = String.valueOf(showCityPois.size()) + mapActivity.getString(R.string.nav_foot_print_pois);
                    footPrintModel.poiCount = getPoiCountBySeqId(seqId) + mapActivity.getString(R.string.nav_foot_print_pois);
                    navMyFootPrintView.showBottomMsg(footPrintModel);
                }
            }
        }
    }

    private void setCityRank(FootPrintModel footPrintModel) {
        if (summaryPois == null || summaryPois.isEmpty() || footPrintModel == null)
            return;
        else {
            for (int i = 0, j = summaryPois.size(); i < j; i++) {
                if (summaryPois.get(i).cityName.equalsIgnoreCase(footPrintModel.title)) {
                    if (!CommonUtil.isNull(summaryPois.get(i).cityRank))
                        footPrintModel.rank = summaryPois.get(i).cityRank + "%";
                    break;
                }
            }
        }
    }


    private FootPrintModel getSummaryFootPrintModel(String seqId) {
        if (showCityPois == null || showCityPois.size() == 0) return null;
        FootPrintModel footPrintModel = new FootPrintModel();
//        footPrintModel.poiCount = String.valueOf(showCityPois.size());
        footPrintModel.poiCount = getPoiCountBySeqId(seqId);
        footPrintModel.cityName = showCityPois.get(0).cityName;
        footPrintModel.latLng = getLatLngBySeqId(seqId);
        log.i("getSummaryFootPrintModel footPrintModel" + footPrintModel + ",seqId=" + seqId);
        return footPrintModel;
    }

    private CompositeSubscription compositeSubscription = new CompositeSubscription();

    /**
     * 传给后台参数需要的是城市，所以需要根据seqid 转成对应得城市
     */
    private void doGetCityFootPrints(final String city, final String seqId, final FootPrintMapOperation operation) {
        Subscription subscription = navService.doGetFootPrintByCity(city)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<List<MyFootprintDTO>>() {
                    @Override
                    public void call(List<MyFootprintDTO> s) {
                        generateFootPrintByCity(s, seqId, operation);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                    }
                });
        compositeSubscription.add(subscription);
    }

    /**
     * 传给后台参数需要的是城市，所以需要根据seqid 转成对应得城市
     */
    private void doGetCityFootPrints(final String city, final String seqId, final FootPrintMapOperation operation, final Marker marker) {
        Subscription subscription = navService.doGetFootPrintByCity(city)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<List<MyFootprintDTO>>() {
                    @Override
                    public void call(List<MyFootprintDTO> s) {
//                        s = prduceDetailTestData();
                        generateFootPrintByCity(s, seqId, operation, marker);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                    }
                });
        compositeSubscription.add(subscription);
    }

    /**
     * 测试数据
     *
     * @return
     */
    private List<MyFootprintDTO> prduceDetailTestData() {
        List<MyFootprintDTO> list = new ArrayList<>();
        MyFootprintDTO dto;
        String[] lats = {"31.1499638270", "31.1850138743", "31.0649884553", "30.9828988704", "30.9972489887"};
        String[] lngs = {"121.4157284424", "121.2517722192", "121.2724839065", "121.6254466078", "121.8599972272"};
        for (int i = 0; i < 5; i++) {
            dto = new MyFootprintDTO();
            dto.setSeqId(Constants.FAKE_SEQ_ID_PREFIX + 0);
            dto.setDestStreetNum(i + "");
            dto.setDestStreetName("上海街道" + i);
            dto.setDestCity("上海");
            dto.setDestLatitude(lats[i]);
            dto.setDestLongitude(lngs[i]);
            list.add(dto);
        }
        return list;
    }

    private void generateFootPrintByCity(List<MyFootprintDTO> myFootprintDTOs, final String seqId, FootPrintMapOperation operation) {
        List<FootPrintModel> footPrintModels = new ArrayList<>();
        if (myFootprintDTOs != null && myFootprintDTOs.size() > 0) {
            for (MyFootprintDTO myFootprintDTO : myFootprintDTOs) {
                FootPrintModel footPrintModel = new FootPrintModel();
                footPrintModel.cityName = myFootprintDTO.getDestCity();
                footPrintModel.destStreetName = myFootprintDTO.getDestStreetName();
                footPrintModel.latLng = new LatLng(Double.valueOf(myFootprintDTO.getDestLatitude()), Double.valueOf(myFootprintDTO.getDestLongitude()));
                footPrintModel.seqId = myFootprintDTO.getSeqId();
                /**
                 * 后台返回的seqid，用来对应他的城市
                 */
//                cityLatLng.put(seqId, footPrintModel);
                footPrintModels.add(footPrintModel);
            }
            /**
             * 城市概略点为key，value为其内的左右足迹点
             */
            latLngListMap.put(seqId, footPrintModels);
            log.i("概略点的seqid-->内部所有足迹" + latLngListMap);

        }
        /**
         * 防止多次反复请求
         */
        showCityPois = latLngListMap.get(seqId);
        log.i("generateFootPrintByCity city pois" + showCityPois + ",seqId=" + seqId);
        if (operation == FootPrintMapOperation.SHOW_ALL_SUMMARY || operation == FootPrintMapOperation.SHOW_CITY_POIS) {
            if (showCityPois != null && showCityPois.size() > 0) {
                getCurrentShowCityPois(seqId, operation);
            }
        }
    }

    private void generateFootPrintByCity(List<MyFootprintDTO> myFootprintDTOs, final String seqId, FootPrintMapOperation operation, Marker marker) {
        List<FootPrintModel> footPrintModels = new ArrayList<>();
        if (myFootprintDTOs != null && myFootprintDTOs.size() > 0) {
            for (MyFootprintDTO myFootprintDTO : myFootprintDTOs) {
                FootPrintModel footPrintModel = new FootPrintModel();
                footPrintModel.cityName = myFootprintDTO.getDestCity();
                footPrintModel.destStreetName = myFootprintDTO.getDestStreetName();
                footPrintModel.latLng = new LatLng(Double.valueOf(myFootprintDTO.getDestLatitude()), Double.valueOf(myFootprintDTO.getDestLongitude()));
                footPrintModel.seqId = myFootprintDTO.getSeqId();
                footPrintModels.add(footPrintModel);
            }
            /**
             * 城市概略点为key，value为其内的左右足迹点
             */
            latLngListMap.put(seqId, footPrintModels);
        }
        /**
         * 防止多次反复请求
         */
        showCityPois = latLngListMap.get(seqId);
        log.i("generateFootPrintByCity city pois in summary" + showCityPois + ",seqId=" + seqId);
        if (operation == FootPrintMapOperation.SHOW_SUMMARY_WINDOW_INFO) {
            getSummaryCityPois(marker, seqId);
        }
    }
//    /**
//     * @param *seqId 均为每个城市的最后一次到过的坐标
//     */
//    public void showCityPoiByLtns(List<String> seqIds) {
//        int cityCount = 0;
//        int poiCount = 0;
//        if (seqIds == null || seqIds.size() == 0) return;
//        for (String seqId : seqIds) {
//            cityCount = cityCount + 1;
//            List<FootPrintModel> footPrintModels = latLngListMap.get(seqId);
//            if (footPrintModels == null || footPrintModels.size() == 0) {
//                doGetCityFootPrints(getCityNameBySeqId(seqId), seqId, false);
//            } else {
//                poiCount = poiCount + footPrintModels.size();
//            }
//        }
//        if (navMyFootPrintView != null && summaryPois.size() > 0) {
//            FootPrintModel footPrintModel = new FootPrintModel();
//            footPrintModel.poiCount = poiCount + mapActivity.getString(R.string.nav_foot_print_pois);
//            footPrintModel.title = cityCount + mapActivity.getString(R.string.nav_foot_print_citys);
//            navMyFootPrintView.showBottomMsg(footPrintModel);
//        }
//    }

    public void getPoiDetail(LatLng latLng, Marker currentMarker) {
        this.currentMarker = currentMarker;
//        mapHandler.geoCoderGps(latLng.latitude, latLng.longitude, LocationType.FOOTPRINT);

        if (navMyFootPrintView != null) {
            navMyFootPrintView.showPopWindowInfo(currentMarker, null);
        }
    }

    @Override
    public void onFindLocateSuccess(PoiItemInfo poiItemInfo) {
        if (navMyFootPrintView != null) {
            currentMarker.setTitle(poiItemInfo.getTitle());
            navMyFootPrintView.showPopWindowInfo(currentMarker, new LatLng(poiItemInfo.getLatitude(), poiItemInfo.getLongitude()));
        }
    }

    @Override
    public void onFindLocateFail() {

    }

    public String getCityNameBySeqId(String seqId) {
        if (cityLatLng.get(seqId) != null) {
            return cityLatLng.get(seqId).cityName;
        }
        return null;
    }

    public LatLng getLatLngBySeqId(String seqId) {
        if (cityLatLng.get(seqId) != null) {
            return cityLatLng.get(seqId).latLng;
        }
        return null;
    }

    public String getPoiCountBySeqId(String seqId) {
        if (cityLatLng.get(seqId) != null) {
            return cityLatLng.get(seqId).poiCountInCity;
        }
        return null;
    }

    public String getCityPoiCountBySeqId(String seqId) {
        if (cityLatLng.get(seqId) != null) {
            return cityLatLng.get(seqId).poiCount;
        }
        return null;
    }


    public void deleteCityPoi(final Marker marker, final String seqId) {

        if (CommonUtil.isNull(seqId)) return;
        subscription = navService.doDeleteCityPoi(seqId)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (Constants.RES_CODE_SUCCESS.equals(s)) {
                            /**
                             * 逻辑删除当前poi
                             */
                            if (navMyFootPrintView != null) {
                                if (showCityPois != null && showCityPois.size() > 0) {
                                    for (int i = 0; i < showCityPois.size(); i++) {
                                        if (showCityPois.get(i).seqId.equals(seqId)) {
                                            showCityPois.remove(i);
                                            break;
                                        }
                                    }
                                    latLngListMap.put(seqId, showCityPois);
                                }
                                navMyFootPrintView.showDeletePoiCallBackMsg(true, marker);
                            }
                        } else {
                            if (navMyFootPrintView != null) {
                                navMyFootPrintView.showDeletePoiCallBackMsg(false, marker);
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (navMyFootPrintView != null) {
                            navMyFootPrintView.showDeletePoiCallBackMsg(false, marker);
                        }
                    }
                });
        compositeSubscription.add(subscription);
    }

    public void loadOverViewShareUrl(String longitude, String latitude) {
        Subscription subscription = navService.doGetOverViewFootPrintShareUrl(longitude, latitude)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String str) {
                        if (!TextUtils.isEmpty(str))
                            navMyFootPrintView.showShareDialog(str);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        navMyFootPrintView.showLoadShareUrlErr(throwable);
                    }
                });
        compositeSubscription.add(subscription);
    }

    public void loadDetailShareUrl(String longitude, String latitude, String city, String scale) {
        Subscription subscription = navService.doGetDetailFootPrintShareUrl(longitude, latitude, city, scale)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String str) {
                        if (!TextUtils.isEmpty(str))
                            navMyFootPrintView.showShareDialog(str);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        navMyFootPrintView.showLoadShareUrlErr(throwable);
                    }
                });
        compositeSubscription.add(subscription);
    }

    public void unsubscribe() {
        if (compositeSubscription != null && !compositeSubscription.isUnsubscribed()) {
            compositeSubscription.unsubscribe();
        }
        mapHandler.removeOnMapFootPrintCallBack();
    }
}
